import inquirer from "inquirer";
import {Addon, findRushJSON} from "./addon.mjs";
import {projects} from "./app-setting.json.mjs";
import {loaderType} from "./loader-type.mjs";

const addon = new Addon();

target_project()
  .then((answer) => {
    addon.setPosition(answer.target_project);
  })
  .then(() => {
    return selectLoaderType();
  })
  .then((loader_type) => {
    addon.setLoaderType(loader_type.loader_type)
    return addon_info();
  })
  .then((info) => {
    addon.create(info);
    console.log("成功创建插件");
  });


function addon_info() {
  const needInfo = {
    entityName: "xxx",
    contributes: "xxx",
    cpName: "xxx",
    cp: "xxx",
    implClassName: "xxx",
    publisher: "xxx", // TODO 读git的username
  };
  const defaultValue = {
    contributes: "views",
  }
  const keys = Object.keys(needInfo);

  const questions = keys.map((key) => {
    const question = {
      type: "input",
      name: key,
      message: `enter ${key}`,
    };
    if (defaultValue[key]) {
      question.default = function () {
        return defaultValue[key];
      };
    }
    return question;
  });

  return inquirer.prompt(questions);
}

/**
 *
 * @returns {Promise<{target_project: {Name: string, AbsPath: string}}>}
 */
function target_project() {
  const p = findRushJSON()
  if (!p) {
    console.error('请在front-theory目录及其子目录下执行');
    process.exit(1);
  }
  return inquirer.prompt([
    {
      type: "list",
      name: "target_project",
      message: "选择创建插件和Loader的项目",
      choices: projects.map((project) => {
        return {
          name: project.Name,
          value: project,
          short: project.Name + 'The long option',
        };
      }),
    },
  ]);
}


/**
 *
 * @returns {Promise<{loader_type: string}>}
 */
function selectLoaderType() {
  return inquirer.prompt([
    {
      type: "list",
      name: "loader_type",
      message: "选择Loader",
      choices: loaderType.map((item) => {
        return {
          name: item.name + ` (${item.description})`,
          value: item.name,
        };
      }),
    },
  ]);
}